var BASE_URL = window.parent.ADIMIN_XIUJIADIAN_COM;
var layer = layui.layer;

var sdutyTime = {
    _holiday: {
        "2017-01-01": "元旦",
        "2017-01-27": "除夕",
        "2017-01-28": "春节",
        "2017-04-04": "清明节",
        "2017-05-01": "劳动节",
        "2017-05-30": "端午节",
        "2017-10-01": "国庆节",
        "2017-10-04": "中秋节"
    },
    _weekArray: ["周日", "周一", "周二", "周三", "周四", "周五", "周六"],
    _calendarDate: [],								//日期数据
    _calendarDatePanel: $("#calendarDate tbody"),	//日期显示容器
    _calendarTimePanel: $("#calendarTime tbody"),	//时间显示容器
    _curDatePanel: $("#curDate"),
    _selectedDate: null,		//参数.年月日
    _selectedTime: null,		//参数. 时分
    _cityId: null,			//参数 城市ID
    _productId: null,		//参数 产品ID
    //_orderId: null,		//参数 产品ID
    _layerIndex: null,		//参数.layer index
    _callBack: null,			//参数.callBack 函数

    //初始化
    init: function (params) {
        var self = this;

        //初始化参数
        self._selectedDate = params.selectedDate;
        self._cityId = params.cityId;
        self._productId = params.productId;
        self._selectedTime = params.selectedTime;
        //self._orderId = params.orderId;

        self._layerIndex = params.layerIndex;
        self._callBack = params.callBack;

        //初始化当前时间
        self._curDatePanel.text(new Date().getFullYear() + '年' + (new Date().getMonth() + 1) + '月');

        //初始化日期数组
        self._initCalendarDate();
        self._initCalendarTime();

        //展示日期
        self._showCalendarDate();
    },
    //确认选择
    confirm: function () {
        var self = this;
        var $datePanel = self._calendarDatePanel;
        var $timePanel = self._calendarTimePanel;
        var $dtd = $datePanel.find("td.selected");
        var $ttd = $timePanel.find("td.selected");
        var week = $dtd.data("week");
        var date = $dtd.data('date');
        var time = $ttd.data('time');


        if (!(date && time)) {
            alert('请选择时间~', {skin: 'layui-layer-lan'});
            return;
        }

        if (self._getDate(0).date == date) {
            week = '今天';
        }
        self._callBack(date, time, week);
        self.cancel();
    },
    //取消
    cancel: function () {
        var self = this;
        parent.layer.close(self._layerIndex);
    },
    //展示日期
    _showCalendarDate: function () {
        var self = this;
        var calendarDates = self._calendarDate;
        var $panel = self._calendarDatePanel;

        var len = calendarDates.length;

        var $tr = $("<tr></tr>");
        for (var ind in calendarDates) {
            var calendarDate = calendarDates[ind];

            var std = "<td> <span class='date'>" + calendarDate.date.split("-")[2] + "</span></td>";

            //有效日期绑定事件
            var $td = !calendarDate.disabled ? $(std).click(function () {
                self._clickDate(this);
            }) : $(std);

            $td.attr("data-week", calendarDate.week);
            $td.attr("data-date", calendarDate.date);

            //判断节假日
            var holiday = self._holiday[calendarDate.date];
            if (holiday) {
                $td.append($('<span class=\'holiday\'>' + holiday + '</span>'));
            }

            if (calendarDate.disabled) {
                $td.addClass("disabled");
            } else if (!self._selectedDate) {
                $td.addClass("selected")
                self._selectedDate = calendarDate.date;
            } else if (self._selectedDate == calendarDate.date) {
                $td.addClass("selected")
            }

            $tr.append($td);

            if (((+ind) + 1) % 7 == 0 || (+ind + 1) == len) {
                $panel.append($tr);
                $tr = $("<tr></tr>");
            }
        }

        self._showCalendarTime(self._selectedDate);
    },
    //展示时间
    _showCalendarTime: function (date) {
        var self = this;
        var calendarDates = self._calendarDate;

        var times = [];
        for (var ind in calendarDates) {
            var calendarDate = calendarDates[ind];
            if (calendarDate.date == date) {
                times = calendarDate.time;
                break;
            }
        }

        var $panel = self._calendarTimePanel;
        var len = times.length;

        self._getSche(date, function (res) {

            var $tr = $("<tr></tr>");
            for (var ind in times) {
                var time = times[ind];
                time.disabled = res[ind] == '0';

                var std = "<td><span class='time-span'>" + time.time + "</span></td>";

                //有效日期绑定事件
                var $td = !time.disabled ? $(std).click(function () {
                    self._clickTime(this);
                }) : $(std);

                if (time.disabled) {
                    $td.addClass("disabled");
                } else if (date == self._selectedDate && self._selectedTime && time.time == self._selectedTime) {
                    $td.addClass("selected");
                }

                $td.attr("data-time", time.time);

                $tr.append($td);

                if (((+ind) + 1) % 7 == 0 || (+ind + 1) == len) {
                    $panel.append($tr);
                    $tr = $("<tr></tr>");
                }
            }
        });

    },
    _getSche: function (date, callBack) {
        var self = this;

        var url = BASE_URL + '/or/order_schedule!getSchedule.action?';
        url += 'params.cityId=' + self._cityId;
        url += '&params.productId=' + self._productId;
        // url += '&params.orderId=' + self._orderId;
        url += '&params.scheDate=' + date;

        // $.get(url, function (res) {
        //     callBack(res);
        // });
        $.ajax({
            xhrFields: {withCredentials: true},
            crossDomain: true,
            type: "GET",
            url: url,
            success: function (res) {
                callBack(res);
            }
        });
    },
    //日期点击事件
    _clickDate: function (that) {
        var self = this;
        var $timePanel = self._calendarTimePanel;
        var $datePanel = self._calendarDatePanel;
        var $td = $(that);

        $datePanel.find("td").removeClass("selected");
        $td.addClass("selected");
        $timePanel.empty();

        self._showCalendarTime($td.data('date'));
        self._selectedTime = null;
    },

    //日期点击事件
    _clickTime: function (that) {
        var self = this;
        var $timePanel = self._calendarTimePanel;
        var $td = $(that);
        $timePanel.find("td").removeClass("selected");
        $td.addClass("selected");
    },

    //初始化日期
    _initCalendarDate: function () {
        var self = this;
        var day = new Date().getDay();
        day = day == 0 ? 6 : day - 1;
        for (var i = 0 - day; i < 15; i++) {
            var cdate = self._getDate(i);
            i < 0 ? cdate.disabled = true : cdate.disabled = false;
            i == 0 ? cdate.nowDate = true : cdate.nowDate = false;
            self._calendarDate.push(cdate);
        }
    },

    //初始化日期对应时间
    _initCalendarTime: function () {
        var self = this;
        var calendarDate = self._calendarDate;
        for (var ind in calendarDate) {
            var cdate = calendarDate[ind];
            var calendarTime = [];
            for (var i = 0; i <= 47; i++) {
                var hour = Math.floor(i / 2);
                var min = i % 2 == 0 ? "00" : "30";

                var time = {time: hour + ":" + min};

                var nHour = new Date().getHours();
                var nMin = new Date().getMinutes();

//					var sub = Math.ceil(nHour*2 + (nMin/30));
                var sub = Math.ceil(nHour * 2 + (nMin / 30));

                //前天的和当前时间之前的置灰
                if (cdate.disabled || (cdate.nowDate && i <= sub)) {
                    time.disabled = true;
                } else {
                    time.disabled = false;
                }

                calendarTime.push(time);
            }
            cdate.time = calendarTime;
        }
    },
    //获取日期
    _getDate: function (count) {
        var self = this;
        var date = new Date();
        date.setTime(date.getTime() + (86400000 * count));
        date.getFullYear();
        var y = date.getFullYear();
        var m = date.getMonth() + 1;
        m = m < 10 ? "0" + m : m;
        var d = date.getDate();
        d = d < 10 ? "0" + d : d;
        return {
            date: y + "-" + m + "-" + d,
            dateNum: y + "" + m + "" + d,
            week: (self._weekArray[date.getDay()]),
            weekNum: date.getDay()
        };
    }
};